﻿@using WebAPP.ViewModels
@using WebAPP.HttpClients

@inject ICatalogHttpClient HttpClient

<BSCard CardType="CardType.Card" Padding="Padding.None">
    <BSCard CardType="CardType.Header">
        @if (_isEditingTitle)
        {
            <BSInput InputType="InputType.Text" @bind-Value="@ViewModel.Title"/>
            <BSButton Class="bi bi-pencil-square" Color="BSColor.Warning" OnClick=@(async () => {ToggleTitle(); await ChangeTitleAsync(); })></BSButton>
        }
        else
        {
            @ViewModel.Title
            <BSButton Class="bi bi-pencil-square" Color="BSColor.Warning" OnClick=@(ToggleTitle)></BSButton>
        }
    </BSCard>
    <BSCard CardType="CardType.Image" src="placeholder:286x180"/>
    <BSCard CardType="CardType.Body">
        <BSCard CardType="CardType.Title">@ViewModel.Title</BSCard>
        <BSCard CardType="CardType.Subtitle">
            @if (_isEditingDescription)
            {
                <BSInput InputType="InputType.Text" @bind-Value="@ViewModel.Description"/>
                <BSButton Class="bi bi-pencil-square" Color="BSColor.Warning" OnClick=@(async () => {ToggleDescription(); await ChangeDescriptionAsync(); })></BSButton>
            }
            else
            {
                @ViewModel.Description
                <BSButton Class="bi bi-pencil-square" Color="BSColor.Warning" OnClick=@(ToggleDescription)></BSButton>
            }
        </BSCard>
        <BSButton Class="bi bi-trash3" Color="BSColor.Danger" OnClick="@(DeleteAsync)"></BSButton>
    </BSCard>
    <BSCard CardType="CardType.Footer">Last updated 3 mins ago</BSCard>
</BSCard>

@code {

    [Parameter]
    public CatalogCardViewModel ViewModel { get; set; }

    [Parameter]
    public EventCallback<Guid> OnDeleted { get; set; }

    private readonly CancellationTokenSource _cancellationTokenSource = new();

    private bool _isEditingDescription;
    private bool _isEditingTitle;

    private void ToggleDescription()
        => _isEditingDescription = !_isEditingDescription;

    private void ToggleTitle()
        => _isEditingTitle = !_isEditingTitle;

    private async Task ChangeTitleAsync()
        => await HttpClient.ChangeTitleAsync(ViewModel.Id, ViewModel.Title, _cancellationTokenSource.Token);

    private async Task ChangeDescriptionAsync()
        => await HttpClient.ChangeDescriptionAsync(ViewModel.Id, ViewModel.Description, _cancellationTokenSource.Token);

    private async Task DeleteAsync()
    {
        var response = await HttpClient.DeleteAsync(ViewModel.Id, _cancellationTokenSource.Token);
        if (response.Success) await OnDeleted.InvokeAsync(ViewModel.Id);
    }

    private void Dispose()
        => _cancellationTokenSource.Cancel();

}